'use strict';
import _Promise from 'bluebird';

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

/**
 * 金额保留小数位
 * @param num
 * @param len
 * @returns
 */
function formatNum(num,len) {
	　if (isNaN(num)) { 
		return num.toFixed(len);
	　}else{
		num=Number(num);
		return num.toFixed(len);
	　}
	}

function isFunction(obj) {
  return 'function' == typeof obj;
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/  
function formatTimespan(number,format) {  
  
  var formateArr  = ['Y','M','D','h','m','s'];  
  var returnArr   = [];  
  
  var date = new Date(number * 1000);  
  returnArr.push(date.getFullYear());  
  returnArr.push(formatNumber(date.getMonth() + 1));  
  returnArr.push(formatNumber(date.getDate()));  
  
  returnArr.push(formatNumber(date.getHours()));  
  returnArr.push(formatNumber(date.getMinutes()));  
  returnArr.push(formatNumber(date.getSeconds()));  
  
  for (var i in returnArr)  
  {  
    format = format.replace(formateArr[i], returnArr[i]);  
  }  
  return format;  
}  

function generateNonceString(length) {
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var maxPos = chars.length;
  var noceStr = "";
  for (var i = 0; i < (length || 32); i++) {
    noceStr += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return noceStr;
}

function format(date, fmt) {
  date = new Date(date);
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  }return fmt;
}

function checkMobile(phoneNum) {
  var reg = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
  if (reg.test(phoneNum)) {
    return true;
  }
  return false;
}

function getLocalTime(nS) {
  return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/, ' ');
}

function timeRange(beginTime, endTime) {
  var strb = beginTime.split(":");
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split(":");
  if (stre.length != 2) {
    return false;
  }

  var b = new Date();
  var e = new Date();
  var n = new Date();

  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);

  if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
    return true;
  } else {
    return false;
  }
}

/**
 * @param {Function} fun 接口
 * @param {Object} options 接口参数
 * @returns {Promise} Promise对象
 */
function Promise(fun, options) {
    options = options || {};
    return new _Promise((resolve, reject) => {
        if (typeof fun !== 'function') {
            reject();
        }
        options.success = resolve;
        options.fail = reject;
        fun(options);
    });
}

/**
 * 手势库
 */
function touchstart(e, _this) {
    const t = e.touches[0],
        startX = t.clientX,
        startY = t.clientY;
    _this.setData({
        'gesture.startX': startX,
        'gesture.startY': startY,
        'gesture.out': true
    })
}
/**
 * 左滑
 * @returns {boolean} 布尔值
 */
function isLeftSlide(e, _this) {
    if (_this.data.gesture.out) {
        const t = e.touches[0],
            deltaX = t.clientX - _this.data.gesture.startX,
            deltaY = t.clientY - _this.data.gesture.startY;
            
        if (deltaX < -20 && deltaX > -40 && deltaY < 8 && deltaY > -8) {
            _this.setData({
                'gesture.out': false
            })
            return true;
        } else {
            return false;
        }
    }
}
/**
 * 右滑
 * @returns {boolean} 布尔值
 */
function isRightSlide(e, _this) {
    if (_this.data.gesture.out) {
        const t = e.touches[0],
            deltaX = t.clientX - _this.data.gesture.startX,
            deltaY = t.clientY - _this.data.gesture.startY;

        if (deltaX > 20 && deltaX < 40 && deltaY < 8 && deltaY > -8) {
            _this.setData({
                'gesture.out': false
            })
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 验证字符串是否全部是数字
 * @param theObj
 * @returns
 */
function checkNumber(theObj) {
	  var reg = /^[0-9]+.?[0-9]*$/;
	  if (reg.test(theObj)) {
	    return true;
	  }
	  return false;
}
/**
 * 验证字符串是否全部是汉字
 * @param str
 * @returns
 */
function isChinese(str){
	 var re=/[^\u4e00-\u9fa5]/;  
	 if (re.test(str)) return false ;
	 return true ; 
 }
function extend(target, source) {
    for (var obj in source) {
        target[obj] = source[obj];
    }
    return target;
}

function savePicToAlbum(tempFilePath) {
  let that = this;
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showToast({
                  title: '保存成功'
                });
              },
              fail(res) {
                console.log(res);
              }
            })
          },
          fail() {
            // 用户拒绝授权,打开设置页面
            wx.openSetting({
              success: function (data) {
                console.log("openSetting: success");
              },
              fail: function (data) {
                console.log("openSetting: fail");
              }
            });
          }
        })
      } else {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
            });
          },
          fail(res) {
            console.log(res);
          }
        })
      }
    },
    fail(res) {
      console.log(res);
    }
  })
}

/*获取当前页url*/
function getCurrentPageUrl() {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  return url
}

/*获取当前页带参数的url*/
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  var options = currentPage.options    //如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

  return urlWithArgs
}

module.exports = {
		 Promise: Promise,
		    Gesture: {
		        touchstart: touchstart,
		        isLeftSlide: isLeftSlide,
		        isRightSlide: isRightSlide
		    },
		  formatTime: formatTime,
		  formatTimespan:formatTimespan,
		  isFunction: isFunction,
		  generateNonceString: generateNonceString,
		  format: format,
		  checkMobile: checkMobile,
		  getLocalTime: getLocalTime,
		  timeRange: timeRange,
		  extend:extend,
		  formatNum:formatNum,
		  checkNumber:checkNumber,
		  isChinese:isChinese,
      savePicToAlbum: savePicToAlbum,
      getCurrentPageUrl: getCurrentPageUrl,
      getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs
};